package com.fz.song.springsecurydemo.service;

import com.fz.song.springsecurydemo.entity.McUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;


@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    private ArrayList<McUser> users = new ArrayList<>();

    {
        users.add(new McUser(1, "zhangsan", "$2a$10$7Zr7C7Df9US/uDlM0b/eLuUqpGFm8SBLxYF3eHMNvmmTUjVEXQmsO", "admin"));
        users.add(new McUser(2, "lisi", "$2a$10$lsi6a2YiZh3ihTp/CfMjnuV2H3eLEkz73ABYJMYqQ.t7e1wmnLtTO", "user"));
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("执行loadUserByUsername:{}", username);
        //根据用户名去数据库查询
        McUser mcUser = getUserByUsername(username);
        if (mcUser == null) {
            throw new UsernameNotFoundException("用户名或者密码错误");
        }
        return new User(username, mcUser.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(mcUser.getRole()));
    }

    private McUser getUserByUsername(String username) {
        for (McUser user : users) {
            if (user.getName().equals(username)) {
                return user;
            }
        }
        return null;
    }
}
